from app.schemas.ai_character import AICharacterCreate, AICharacterUpdate, AICharacter
from app.database.connection import get_database
from datetime import datetime
from bson import ObjectId

async def create_ai_character(character: AICharacterCreate) -> AICharacter:
    """创建AI角色"""
    db = get_database()
    
    # 创建角色文档
    character_dict = character.dict()
    character_dict["creator_id"] = ObjectId()  # 这里应该从认证信息中获取用户ID
    character_dict["created_at"] = datetime.utcnow()
    character_dict["updated_at"] = datetime.utcnow()
    character_dict["interaction_count"] = 0
    
    # 插入数据库
    result = await db["ai_characters"].insert_one(character_dict)
    
    # 获取创建的角色
    created_character = await db["ai_characters"].find_one({"_id": result.inserted_id})
    
    # 转换为AICharacter对象
    character_response = created_character.copy()
    character_response["id"] = str(character_response["_id"])
    character_response["creator_id"] = str(character_response["creator_id"])
    
    return AICharacter(**character_response)

async def get_ai_character(character_id: str) -> AICharacter:
    """获取AI角色详情"""
    db = get_database()
    try:
        character_doc = await db["ai_characters"].find_one({"_id": ObjectId(character_id)})
        if character_doc:
            character_response = character_doc.copy()
            character_response["id"] = str(character_response["_id"])
            character_response["creator_id"] = str(character_response["creator_id"])
            return AICharacter(**character_response)
        return None
    except Exception:
        return None

async def get_user_ai_characters(skip: int = 0, limit: int = 100) -> list[AICharacter]:
    """获取用户AI角色列表"""
    db = get_database()
    characters_cursor = db["ai_characters"].find().skip(skip).limit(limit)
    characters = await characters_cursor.to_list(length=limit)
    
    result = []
    for character_doc in characters:
        character_response = character_doc.copy()
        character_response["id"] = str(character_response["_id"])
        character_response["creator_id"] = str(character_response["creator_id"])
        result.append(AICharacter(**character_response))
    
    return result

async def update_ai_character(character_id: str, character_update: AICharacterUpdate) -> AICharacter:
    """更新AI角色"""
    db = get_database()
    
    # 构建更新字典
    update_data = {k: v for k, v in character_update.dict().items() if v is not None}
    if not update_data:
        return await get_ai_character(character_id)
    
    update_data["updated_at"] = datetime.utcnow()
    
    # 更新数据库
    result = await db["ai_characters"].update_one(
        {"_id": ObjectId(character_id)},
        {"$set": update_data}
    )
    
    if result.modified_count == 0:
        return None
    
    return await get_ai_character(character_id)

async def delete_ai_character(character_id: str) -> bool:
    """删除AI角色"""
    db = get_database()
    result = await db["ai_characters"].delete_one({"_id": ObjectId(character_id)})
    return result.deleted_count > 0